package com.easyweb.controller;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easyweb.common.CommonUtils;
import com.easyweb.common.Constants;
import com.easyweb.common.PrintUtils;
import com.easyweb.datasource.DataSourceContextHolder;
import com.easyweb.datasource.DataSourceType;
import com.easyweb.model.ResultMsg;
import com.easyweb.service.TouTiaoService;

@Controller
@RequestMapping("/toutiao")
public class TouTiaoController {
	
	//今日头条首页地址
	public static final String TOUTIAOURL = "http://www.toutiao.com/api/article/feed/?category=__all__&utm_source=toutiao&widen=1";
	
	//头条号主页地址
	public static final String TOUTIAOHAOURL = "http://www.toutiao.com/pgc/ma/?page_type=1&count=10&version=2&platform=pc";
	//
	public static final String TT = "http://www.toutiao.com";
	@Autowired
	private TouTiaoService touTiaoService;
	
	@RequestMapping("/section")
	public void section_avg(HttpServletResponse response){
		DataSourceContextHolder.setDbType(DataSourceType.DS_TOUTIAO);
		List<Map<String,Object>> list = touTiaoService.getSectionAvg();
		DataSourceContextHolder.setDbType(DataSourceType.DS_EASYWEB);
		PrintUtils.printMsg(response, list);
	}
	
	@RequestMapping("/type")
	public void type_avg(HttpServletResponse response){
		DataSourceContextHolder.setDbType(DataSourceType.DS_TOUTIAO);
		List<Map<String,Object>> list = touTiaoService.getTypeAvg();
		DataSourceContextHolder.setDbType(DataSourceType.DS_EASYWEB);
		PrintUtils.printMsg(response, list);
	}
	@RequestMapping("/t")
	public String section(HttpServletResponse response,HttpServletRequest request){
		IndexController.fillHeaderAndFooter(request);
		return "front/toutiao";
	}
	
	@RequestMapping("/count")
	public void count(HttpServletResponse response){
		DataSourceContextHolder.setDbType(DataSourceType.DS_TOUTIAO);
		int article_count = touTiaoService.getArticleCount();
		int author_count = touTiaoService.getAuthorCount();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("article_count", article_count);
		map.put("author_count", author_count);
		DataSourceContextHolder.setDbType(DataSourceType.DS_EASYWEB);
		PrintUtils.printMsg(response, map);
	}
	@RequestMapping("/tophot")
	public void tophot(HttpServletRequest request,HttpServletResponse response){
		String time = request.getParameter("time");
		long hotTime = 0;
		long nextTime = 0;
		Map<String, Object> retMap = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		try {
			hotTime = StringUtils.isEmpty(time)?0:Long.parseLong(time);
		} catch (Exception e) {
			PrintUtils.printMsg(response, new ResultMsg(Constants.STATUS_ERROR,null));
			return;
		}
		String url = TOUTIAOURL + "&max_behot_time="+hotTime+"&max_behot_time_tmp="+hotTime;
		JSONObject param = null;
		param = CommonUtils.getUrlParam();
		url+= "&as=" + param.get("as") + "&cp=" + param.get("cp");
		JSONObject json = null;
		try {
			json = getReturnJson(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(json != null){
			if(json.getBooleanValue("has_more")){
				nextTime = json.getJSONObject("next").getLongValue("max_behot_time");
				JSONArray data = json.getJSONArray("data");
				for(int i=0;i<data.size();i++){
					try{
						JSONObject obj = (JSONObject) data.get(i);
						Map<String, Object> map = new HashMap<String, Object>();
						String title = obj.getString("title");//
						String link = obj.getString("source_url");
						String authorUrl = obj.getString("media_url");//头条号主页url
						if(!"ad".equals(obj.getString("tag"))){
							if(!StringUtils.isEmpty(title)&&!StringUtils.isEmpty(authorUrl)&&!link.contains("?_as_")){
								map.put("title", title);
								map.put("url", TT+link);
								list.add(map);
							}
						}
					}catch (Exception e) {
						System.out.println("error:"+e.getMessage());
					}
				}
			}
		}
		retMap.put("time", nextTime);
		retMap.put("data", list);
		PrintUtils.printMsg(response, retMap);
	}
	
	@RequestMapping("/weare")
	public void getMyTopHot(HttpServletResponse response){
		JSONObject json = getSubPage("52155491628", 0);
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		if(json!=null&&json.getIntValue("has_more")==1){
			JSONArray data = json.getJSONArray("data");
			for(int i=0;i<(data.size()<6?data.size():6);i++){
				try {
					JSONObject obj = (JSONObject) data.get(i);
					String title = obj.getString("title");//标题
					String articleUrl = obj.getString("source_url");
					if(!StringUtils.isEmpty(title)&&!StringUtils.isEmpty(articleUrl)){
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("title", title);
						map.put("url", articleUrl);
						list.add(map);
					}
				} catch (Exception e) {
					System.out.println("error:"+e.getMessage());
				}
			}
		}
		PrintUtils.printMsg(response, list);
	}
		
	private JSONObject getSubPage(String media_id,long hotTime){
		String url = TOUTIAOHAOURL + "&media_id="+media_id+"&max_behot_time="+hotTime;
		JSONObject param = null;
		param = CommonUtils.getUrlParam();
		url+= "&as=" + param.get("as") + "&cp=" + param.get("cp");
		try {
			URL httpUrl = new URL(url);
			BufferedReader in = new BufferedReader( new InputStreamReader(httpUrl.openStream(),"UTF-8") );   
			String line = null;
			String content = "";
			while ((line = in.readLine())!=null) {
				content+=line;
			}
			in.close();
			return JSONObject.parseObject(content);
		} catch (Exception e) {
			System.err.println("访问子页面失败:"+url);
			e.printStackTrace();
		}
		return null;
	}
	
	private JSONObject getReturnJson(String url){
		try{
			URL httpUrl = new URL(url);
			BufferedReader in = new BufferedReader( new InputStreamReader(httpUrl.openStream(),"UTF-8") );   
			String line = null;
			String content = "";
			while ((line = in.readLine())!=null) {
				content+=line;
			}
			in.close();
			return JSONObject.parseObject(content);
		}catch (Exception e) {
			System.err.println("访问失败:"+url);
			e.printStackTrace();
		}
		return null;
	}
	
}
